package com.example.video2

import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.OrientationEventListener
import android.view.SurfaceHolder
import android.view.View
import android.widget.FrameLayout
import android.widget.SeekBar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.controller_layout.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private lateinit var playerViewModel: PlayerViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //设置监听器接收系统的广播事件
        object :OrientationEventListener(this){
            override fun onOrientationChanged(orientation: Int) {
                TODO("Not yet implemented")
            }

        }
        updatePlayerProgress()
        //对liveData进行观察
        playerViewModel = ViewModelProvider(this).get(PlayerViewModel::class.java).apply {
            progressBarVisibility.observe(this@MainActivity, Observer {
                progressBar.visibility =it
            })

            //resize
            videoResolution.observe(this@MainActivity, Observer {
                seekBar.max =mediaPlayer.duration
                //最为消息队列放到最后实现
                playerFragment.post {
                    resizePlayer(it.first,it.second)
                }
            })
            controllerFrameVisibility.observe(this@MainActivity, Observer { controllerFrame.visibility =it })

            bufferPercent.observe(this@MainActivity, Observer { seekBar.secondaryProgress = seekBar.max * it / 100 })

            //观察播放状态 做视图层改变
            playerStatus.observe(this@MainActivity, Observer {
                controllerButton.isClickable =true
                when(it){
                    PlayerStatus.Paused -> controllerButton.setImageResource(R.drawable.ic_baseline_play_arrow_24)
                    PlayerStatus.Completed -> controllerButton.setImageResource(R.drawable.ic_baseline_replay_24)
                    PlayerStatus.NotReady -> controllerButton.isClickable =false
                    else -> controllerButton.setImageResource(R.drawable.ic_baseline_pause_24)
                }
            })

        }
        lifecycle.addObserver(playerViewModel.mediaPlayer)

        //控制状态改变
        controllerButton.setOnClickListener{
            playerViewModel.togglePlayerStatus()
        }
        //点击隐藏seekbar
        playerFragment.setOnClickListener { playerViewModel.toggleControllerVisibility() }
        //拖动seekBar
        seekBar.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if(fromUser){
                    playerViewModel.playerSeekToProgress(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                //TODO("Not yet implemented")
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                //TODO("Not yet implemented")
            }

        })

        surfaceView.holder.addCallback(object :SurfaceHolder.Callback{
            override fun surfaceCreated(p0: SurfaceHolder) {}

            override fun surfaceChanged(holder: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
                playerViewModel.mediaPlayer.setDisplay(holder)
                //播放过程屏幕点亮
                playerViewModel.mediaPlayer.setScreenOnWhilePlaying(true);
                Log.d("TAG", "surfaceChanged: 播放中。。。")
            }

            override fun surfaceDestroyed(p0: SurfaceHolder) {}

        })
    }

    //监听方向改变
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if(resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE){
            hideSystemUI()
            //重新驱动数据适配比例
            playerViewModel.emmitVideoResolution()
        }
    }

    private fun resizePlayer(width:Int,height:Int){
        if(width ==0 || height ==0) return
        surfaceView.layoutParams =FrameLayout.LayoutParams(playerFragment.height*width/height,FrameLayout.LayoutParams.MATCH_PARENT,Gravity.CENTER)
    }

    //跟新seekBar进度 放在协程执行
    private fun updatePlayerProgress(){
        lifecycleScope.launch {
            while (true){
                delay(500)
                seekBar.progress = playerViewModel.mediaPlayer.currentPosition
            }
        }
    }

    //隐藏顶部工具条
    private fun hideSystemUI() {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                // Set the content to appear under the system bars so that the
                // content doesn't resize when the system bars hide and show.
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                // Hide the nav bar and status bar
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
    }
}